package com.example.ssd4.view;

import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.Bloom;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.paint.Color;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;

import javafx.scene.control.Label;


public class LoginDialog extends Application {
    public static Stage thisStage;
    private VBox mainVBox;
    private Button loginBtn;
    private Button signBtn;
    private HBox hBox1;
    private GridPane gridPane;
    private HBox hBox2;
    private HBox hBox3;
    private CheckBox rememberCb;
    private CheckBox autoLoginCb;
    private Label idLbl;
    private Label passwordLbl;
    private TextField textField;
    private PasswordField passwordField;
    private Text text;
    private RegisterDialog registerDialog = null;

    private Label idAlert;
    private Label passwordAlert;
    private Scene scene;

    private static final Duration SLIDE_DURATION = Duration.seconds(3); // 切换图片的持续时间
    private static final String[] IMAGE_PATHS = {
            "/image/bg1_proc.jpg",
            "/image/bg2_proc.jpg",
            "/image/bg3_proc.jpg"
    };

    private int currentImageIndex = 0;
    private ImageView backgroundImageView;

    @Override
    public void start(Stage stage) throws Exception {
        mainVBox = new VBox();
        hBox1 = new HBox();
        gridPane = new GridPane();
        hBox2 = new HBox();
        hBox3 = new HBox();
        mainVBox.setAlignment(Pos.CENTER);
        // 创建根节点
        StackPane root = new StackPane();

        // 创建背景图片的ImageView
        backgroundImageView = new ImageView();
        root.getChildren().add(backgroundImageView);
        mainVBox.getChildren().addAll(hBox1,gridPane,hBox2,hBox3,root);
        // 设置初始背景图片
        setBackgroundImage(IMAGE_PATHS[currentImageIndex]);

        // 创建Timeline对象来切换图片
        Timeline timeline = new Timeline(
                new KeyFrame(SLIDE_DURATION, event -> nextImage())
        );
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();



        scene = new Scene(mainVBox,576,430);
        scene.getRoot().setStyle(
                "-fx-background-image: url("+"file:src/main/resources/image/bg4_proc.jpg"+");");
        initGraphic();
        initAction();
        thisStage = stage;
        thisStage.setOnHidden(windowEvent -> {
            if(registerDialog!=null) {
                registerDialog.close();
            }
        });
        thisStage.setScene(scene);
        thisStage.show();
        autoLogin();
    }

    private void nextImage() {
        currentImageIndex = (currentImageIndex + 1) % IMAGE_PATHS.length;
        setBackgroundImage(IMAGE_PATHS[currentImageIndex]);
    }

    private void setBackgroundImage(String imagePath) {
        Image image = new Image(getClass().getResourceAsStream(imagePath));
        backgroundImageView.setImage(image);
    }

    private void initGraphic() {
        Insets margin = new Insets(25,0,0,0);
        //Title
        text = new Text("本科教务系统");
        text.setFont(Font.font("微软雅黑", FontWeight.BOLD,30));
        mainVBox.setMargin(hBox1,margin);
        hBox1.setAlignment(Pos.TOP_CENTER);
        hBox1.getChildren().addAll(text);

        //Username Password
        idLbl = new Label("用户名:");
        idLbl.setStyle("-fx-font-size: 15px;");
        idLbl.setAlignment(Pos.CENTER);
        passwordLbl = new Label("密码:");
        passwordLbl.setStyle("-fx-font-size: 15px;");
        passwordLbl.setAlignment(Pos.CENTER);
        idLbl.setMinWidth(80);
        passwordLbl.setMinWidth(80);
        textField = new TextField();
        textField.setPromptText("请输入学号/工号");
        passwordField = new PasswordField();
        passwordField.setPromptText("请输入密码");
        idAlert=new Label("");
        passwordAlert=new Label("");

        gridPane.add(idLbl,0,0);
        gridPane.add(textField,1,0);
        gridPane.add(idAlert,1,1);
        gridPane.add(passwordLbl,0,2);
        gridPane.add(passwordField,1,2);
        gridPane.add(passwordAlert,1,3);
        gridPane.setAlignment(Pos.CENTER);

        //Remember AutoLogin
        rememberCb = new CheckBox("记住密码");
        autoLoginCb = new CheckBox("自动登录");
        hBox2.getChildren().addAll(rememberCb,autoLoginCb);
        rememberCb.setStyle("-fx-font-size: 15px;");
        rememberCb.addEventHandler(MouseEvent.MOUSE_ENTERED,
                new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        Bloom bloom = new Bloom();
                        bloom.setThreshold(1.0);
                        rememberCb.setEffect(bloom);
                    }
                });
        rememberCb.addEventHandler(MouseEvent.MOUSE_EXITED,
                new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        rememberCb.setEffect(null);
                    }
                });
        autoLoginCb.addEventHandler(MouseEvent.MOUSE_ENTERED,
                new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        Bloom bloom = new Bloom();
                        bloom.setThreshold(1.0);
                        autoLoginCb.setEffect(bloom);
                    }
                });
        autoLoginCb.addEventHandler(MouseEvent.MOUSE_EXITED,
                new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        autoLoginCb.setEffect(null);
                    }
                });
        autoLoginCb.setStyle("-fx-font-size: 15px;");
        hBox2.setAlignment(Pos.CENTER);

        //Login Sign
        loginBtn = new Button("登录");
        loginBtn.setStyle(
                "-fx-pref-width: 150px;-fx-pref-height: 20px;"+
                        "-fx-background-color: DARKBLUE;"+
                        "-fx-border-radius: 60px;"+
                        "-fx-font-size: 15px;"+
                        "-fx-text-fill: WHITE;"+
                        "-fx-font-weight: bold;");
        signBtn = new Button("注册");
        signBtn.setStyle(
                "-fx-background-color: transparent;" +
                        "-fx-border-color: transparent;" +
                        " -fx-text-fill: BLUE;" +
                        " -fx-underline: true;" +
                        "-fx-font-size: 15px;" +
                        " -fx-cursor: hand;");
        hBox3.getChildren().addAll(signBtn,loginBtn);

        //布局调整
        mainVBox.setPadding(new Insets(20));
        mainVBox.setSpacing(20);
        gridPane.setVgap(10);
        gridPane.setHgap(10);
        hBox2.setSpacing(100);
        hBox3.setAlignment(Pos.CENTER);
        hBox3.setSpacing(30);

    }

    private void initAction() {

        // 创建一个 KeyCodeCombination，表示按下 Esc 键
        KeyCodeCombination closeCombination = new KeyCodeCombination(KeyCode.ESCAPE);

        // 设置快捷键的处理
        scene.setOnKeyPressed(event -> {
            if (closeCombination.match(event)) {
                // 在这里执行关闭窗口的操作
                thisStage.close();
            }
        });


        idLbl.setOnMouseClicked(event -> {
            textField.requestFocus();
            textField.selectAll();  // 全选TextField中的文本
        });
        passwordLbl.setOnMouseClicked(event -> {
            passwordField.requestFocus();
            passwordField.selectAll();  // 全选TextField中的文本
        });
            passwordField.focusedProperty().addListener((observable, oldValue, newValue) -> {
                if (!newValue) {
                    // 当失去焦点时触发的事件
                    if(ifPasswordLegal())
                    {
                    }else {
                        passwordAlert.requestFocus();
                        passwordAlert.setTextFill(Color.RED);
                        passwordAlert.setText("!密码不能为空");

                    }

                }
            });

        textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                // 当失去焦点时触发的事件
               if(ifIDLegal())
               {

               }else {
                   textField.requestFocus();
                   idAlert.setTextFill(Color.RED);
                   idAlert.setText("!用户名不能为空");
               }
            }
        });

        textField.setOnAction(event -> {

            if (ifIDLegal()) {
                // 如果正确，选中passwordfield
                passwordField.requestFocus();

            } else {
                // 如果错误，全选textfiled
                textField.requestFocus();
                textField.selectAll();
            }
        });

        passwordField.setOnAction(actionEvent -> {

            if(ifPasswordLegal())
            {
                if(validate()) {
                    if(textField.getText().replaceAll(" ","").length()==5){
                        StudentDialog studentDialog = new StudentDialog();
                        studentDialog.initAccount(textField.getText().replaceAll(" ",""));
                        try {
                            studentDialog.start(new Stage());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        TeacherDialog teacherDialog = new TeacherDialog();
                        teacherDialog.initAccount(textField.getText().replaceAll(" ",""));
                        try {
                            teacherDialog.start(new Stage());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    setAutoLogin();
                    thisStage.hide();
                }

            }
            else{
                passwordField.requestFocus();
                passwordField.selectAll();
            }

        });

        passwordField.setOnMouseClicked(event -> {
            if(!ifIDLegal())
            {
                textField.requestFocus();
            }
        });


        textField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if(textField.getText().length()!=3&&textField.getText().length()!=5)
                {
                    idAlert.setTextFill(Color.RED);
                    idAlert.setText("!用户名需为3或5个字符");
                }
                else{

                    idAlert.setText(" ");
                }
            }
        });


        passwordField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if(passwordField.getText().length()<5)
                {
                    passwordAlert.setTextFill(Color.RED);
                    passwordAlert.setText("!密码不少于5个字符");

                }else{
                    passwordAlert.setText(" ");
                }

            }
        });


        loginBtn.setOnAction(actionEvent -> {
            if(validate()) {
                if(textField.getText().replaceAll(" ","").length()==5){
                    StudentDialog studentDialog = new StudentDialog();
                    studentDialog.initAccount(textField.getText().replaceAll(" ",""));
                    try {
                        studentDialog.start(new Stage());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else{
                    TeacherDialog teacherDialog = new TeacherDialog();
                    teacherDialog.initAccount(textField.getText().replaceAll(" ",""));
                    try {
                        teacherDialog.start(new Stage());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                setAutoLogin();
                thisStage.close();
            }
        });
       signBtn.setOnAction(actionEvent -> {
           if(registerDialog==null) {
               registerDialog = new RegisterDialog();
               try {
                   registerDialog.start(new Stage());
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
           else {
               registerDialog.setTop();
               registerDialog.setNotTop();
           }
       });
       autoLoginCb.setOnAction(actionEvent -> {
           if(autoLoginCb.isSelected())
           rememberCb.setSelected(true);
       });
    }
    private boolean ifIDLegal()
    {
        if(textField.getText().replaceAll(" ", "").isEmpty())
        {   idAlert.setTextFill(Color.RED);
            idAlert.setText("！用户名不能为空");
            return false;
        }else {
            idAlert.setTextFill(Color.GREEN);
            idAlert.setText("用户名合规");
            return true;
        }

    }
    private boolean ifPasswordLegal(){
        if(passwordField.getText().replaceAll(" ", "").isEmpty())
        {   passwordAlert.setTextFill(Color.RED);
            passwordAlert.setText("！密码不能为空");
            return false;
        }else{
            passwordAlert.setTextFill(Color.GREEN);
            passwordAlert.setText("密码合规");
            return true;
        }

    }


    //validate只需要去验证账户是否存在
    private boolean validate(){
        if(textField.getText().replaceAll(" ","").length()==0)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("账号不能为空");
            textField.setText("账号不能为空");
            textField.requestFocus();
            alert.showAndWait();
            return false;
        }
        else if(passwordField.getText().replaceAll(" ","").length()==0)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("密码不能为空");
            passwordAlert.setText("密码不能为空");
            passwordField.requestFocus();
            alert.showAndWait();
            return false;
        }
      else if(textField.getText().replaceAll(" ","").length()==5){
            //学生端处理
            try (BufferedReader reader = new BufferedReader(new FileReader("src\\main\\resources\\data\\user.log"))) {
                // 读取文件内容
                String line;
                while((line = reader.readLine()) != null) {
                    String regex = "\"([^\"]*)\"";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(line);
                    List<String> data=new ArrayList<>();
                    while (matcher.find()) {
                        data.add(matcher.group(1));
                    }
                    if(data.get(0).equals("S")){
                        if(textField.getText().replaceAll(" ","").equals(data.get(1))){
                            if(passwordField.getText().replaceAll(" ","").equals(data.get(2))){
                                return true;
                            }
                            else {
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("");
                                alert.setHeaderText("Sorry");
                                alert.setContentText("密码错误");
                                passwordAlert.setText("密码错误");
                                passwordField.requestFocus();
                                passwordField.selectAll();
                                alert.showAndWait();
                                return false;
                            }
                        }
                    }
                }
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("");
                alert.setHeaderText("Sorry");
                alert.setContentText("账号不存在");
                idAlert.setText("账号不存在");
                textField.requestFocus();
                textField.selectAll();
                alert.showAndWait();
                return false;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(textField.getText().replaceAll(" ","").length()==3){
            //教师端处理
            try (BufferedReader reader = new BufferedReader(new FileReader("src\\main\\resources\\data\\user.log"))) {
                // 读取文件内容
                String line;
                while((line = reader.readLine()) != null) {
                    String regex = "\"([^\"]*)\"";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(line);
                    List<String> data=new ArrayList<>();
                    while (matcher.find()) {
                        data.add(matcher.group(1));
                    }
                    if(data.get(0).equals("T")){
                        if(textField.getText().replaceAll(" ","").equals(data.get(1))){
                            if(passwordField.getText().replaceAll(" ","").equals(data.get(2))){
                                return true;
                            }
                            else {
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("");
                                alert.setHeaderText("Sorry");
                                alert.setContentText("密码错误");
                                passwordAlert.setText("密码错误");
                                passwordField.requestFocus();
                                passwordField.selectAll();
                                alert.showAndWait();
                                return false;
                            }
                        }
                    }
                }
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("");
                alert.setHeaderText("Sorry");
                alert.setContentText("账号不存在");
                idAlert.setText("账号不存在");
                textField.requestFocus();
                textField.selectAll();
                alert.showAndWait();
                return false;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            //非法处理
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("账号不存在");
            idAlert.setText("账号不存在");
            textField.requestFocus();
            textField.selectAll();
            alert.showAndWait();
            return false;
    }
    private void autoLogin(){
        try (BufferedReader reader = new BufferedReader(new FileReader("src\\main\\resources\\data\\login.log"))) {
            // 读取文件内容
            String line;
            if ((line = reader.readLine()) != null) {
                String regex = "\"([^\"]*)\"";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(line);
                List<String> data = new ArrayList<>();
                while (matcher.find()) {
                    data.add(matcher.group(1));
                }
               if(Objects.equals(data.get(0), "1")&&Objects.equals(data.get(1), "0")){
                   textField.setText(data.get(2));
                   passwordField.setText(data.get(3));
                   rememberCb.setSelected(true);
                }
                else if((Objects.equals(data.get(0), "1")&&Objects.equals(data.get(1), "1"))){
                   textField.setText(data.get(2));
                   passwordField.setText(data.get(3));
                   rememberCb.setSelected(true);
                   autoLoginCb.setSelected(true);
                   autoLoginDelay();
                }

            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void setAutoLogin(){
        try (RandomAccessFile file = new RandomAccessFile("src\\main\\resources\\data\\login.log", "rw")) {
            file.setLength(0); // 将文件截断为0字节
        } catch (IOException e) {
            e.printStackTrace();
        }
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("src\\main\\resources\\data\\login.log", true))) {
                String data="";
                if(autoLoginCb.isSelected()){
                    data = "\"1\",\"1\",\"";
                }else if(rememberCb.isSelected()){
                    data="\"1\",\"0\",\"";
                }else {
                    data="\"0\",\"0\",\"";
                }
                data+=textField.getText().replaceAll(" ","");
                data+="\",\"";
                data+=passwordField.getText().replaceAll(" ","");
                data+="\"";
                writer.write(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    private void autoLoginDelay(){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("自动登录");
        alert.setContentText("自动登录中...");

        //自定义按钮
        alert.getButtonTypes().clear();
        ButtonType cancelButton = new ButtonType("取消");
        alert.getButtonTypes().addAll(cancelButton);

        PauseTransition delay = new PauseTransition(Duration.seconds(3));
        delay.setOnFinished(event -> {
            alert.close();
            loginBtn.fire();
        });
        delay.play();

        // 显示对话框并等待用户响应
        alert.showAndWait().ifPresent(response -> {
            if (response == cancelButton) {
                delay.stop();
                autoLoginCb.setSelected(false);
                alert.close();
            }
        });
    }
    public void setRegisterDialogNull(){
        registerDialog=null;
    }

    static void addGlobalShortcut(Scene scene) {
        KeyCombination exitCombination = new KeyCodeCombination(KeyCode.ESCAPE, KeyCombination.SHIFT_DOWN);
        scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
            if (exitCombination.match(event)) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("返回");
                alert.setHeaderText("确认操作");
                alert.setContentText("你确定要退出程序吗？");

                // 创建自定义按钮
                ButtonType confirmButtonType = new ButtonType("确定", ButtonBar.ButtonData.YES);
                ButtonType cancelButtonType = new ButtonType("取消", ButtonBar.ButtonData.NO);

                // 设置按钮
                alert.getButtonTypes().setAll(cancelButtonType, confirmButtonType);

                Platform.runLater(() -> {
                    Button confirmButton = (Button) alert.getDialogPane().lookupButton(cancelButtonType);
                    confirmButton.setStyle("-fx-background-color: #f87f7f;"); // 设置红色背景
                    alert.getDialogPane().lookupButton(cancelButtonType).requestFocus(); // 设置焦点到"取消"按钮
                });

                // 显示并等待响应
                alert.showAndWait().ifPresent(response -> {
                    if (response == confirmButtonType) {
                        Platform.exit();
                    }
                });

            }
        });
    }
}
